import os
import subprocess
import sys
import time
import signal
import psutil  # 需要安装: pip install psutil

class JavaAppManager:
    def __init__(self, jar_path, log_file="msfiles.log", pid_file="msfiles.pid"):
        self.jar_path = os.path.abspath(jar_path)
        self.log_file = os.path.abspath(log_file)
        self.pid_file = os.path.abspath(pid_file)
        self.process = None

    def start(self):
        if self.is_running():
            print(f"[WARNING] Java app is already running (PID: {self.get_pid()})")
            return False

        try:
            cmd = f"nohup /home/dongman/tools/jdk-17.0.12/bin/java -jar {self.jar_path} > {self.log_file} 2>&1 & echo $!"
            result = subprocess.run(cmd, shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE, universal_newlines=True, check=True)
            pid = int(result.stdout.strip())
            with open(self.pid_file, "w") as f:
                f.write(str(pid))

            print(f"[INFO] Java app started successfully (PID: {pid})")
            return True
        except subprocess.CalledProcessError as e:
            print(f"[ERROR] Failed to start Java app: {e}")
            return False

    def stop(self):
        pid = self.get_pid()
        if not pid:
            print("[WARNING] Java app is not running")
            return False

        try:
            os.kill(pid, signal.SIGTERM)
            print(f"[INFO] Sent SIGTERM to Java app (PID: {pid})")

            for _ in range(10):
                if not self.is_running():
                    print("[INFO] Java app stopped successfully")
                    os.remove(self.pid_file)
                    return True
                time.sleep(1)

            os.kill(pid, signal.SIGKILL)
            print(f"[INFO] Force killed Java app (PID: {pid}) after timeout")
            os.remove(self.pid_file)
            return True
        except ProcessLookupError:
            print("[WARNING] Java app is already stopped")
            os.remove(self.pid_file)
            return True
        except Exception as e:
            print(f"[ERROR] Failed to stop Java app: {e}")
            return False

    def restart(self):
        self.stop()
        time.sleep(1)
        return self.start()

    def status(self):
        if self.is_running():
            print(f"[INFO] Java app is running (PID: {self.get_pid()})")
            return True
        else:
            print("[WARNING] Java app is not running")
            return False

    def is_running(self):
        pid = self.get_pid()
        if not pid:
            return False
        try:
            os.kill(pid, 0)  # 检查 PID 是否存在
            return True
        except ProcessLookupError:
            return False

    def get_pid(self):
        if not os.path.exists(self.pid_file):
            return None
        try:
            with open(self.pid_file, "r") as f:
                pid = int(f.read().strip())
            # 直接检查进程是否存在，而不是调用 is_running()
            try:
                os.kill(pid, 0)  # 检查 PID 是否存在
                return pid
            except ProcessLookupError:
                return None
        except (ValueError, FileNotFoundError):
            return None

    def tail_log(self, lines=100):
        if not os.path.exists(self.log_file):
            print(f"[ERROR] Log file not found: {self.log_file}")
            return

        try:
            cmd = f"tail -n {lines} {self.log_file}"
            subprocess.run(cmd, shell=True, check=True)
        except Exception as e:
            print(f"[ERROR] Failed to tail log: {e}")

def main():
    if len(sys.argv) < 2:
        print("Usage: python manage_java_app.py <start|stop|restart|status|tail> [jar_path]")
        sys.exit(1)

    action = sys.argv[1]
    jar_path = sys.argv[2] if len(sys.argv) > 2 else "msfiles.jar"

    manager = JavaAppManager(jar_path)

    if action == "start":
        manager.start()
    elif action == "stop":
        manager.stop()
    elif action == "restart":
        manager.restart()
    elif action == "status":
        manager.status()
    elif action == "tail":
        manager.tail_log()
    else:
        print(f"[ERROR] Unknown action: {action}")
        sys.exit(1)

# sudo python3 runjar.py start ruoyi-modules-files2.jar
if __name__ == "__main__":
    main()